package registerMvc;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebServlet(name = "ControllerServlet" ,urlPatterns = "/ControllerServlet")
public class ControllerServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-type","text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");
        String email = req.getParameter("email");

        RegisterFormBean formBean = new RegisterFormBean();
        formBean.setName(name);
        formBean.setPassword(password);
        formBean.setPassword2(password2);
        formBean.setEmail(email);

        // 验证参数填写是否符合要求，如果不符合，转发到register.jsp重新填写
        if(!formBean.validate()){
            req.setAttribute("formBean",formBean);
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }

        UserBean userBean = new UserBean();
        userBean.setName(name);
        userBean.setPassword(password);
        userBean.setEmail(email);
        boolean b = DBUtil.getInstance().insertUser(userBean);
        if(!b){
            req.setAttribute("DBMes","你注册的用户已存在");
            req.setAttribute("formBean",formBean);
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }

        resp.getWriter().print("恭喜你注册成功，3秒钟自动跳转");
        req.getSession().setAttribute("userBean",userBean);
        resp.setHeader("refresh","3;url=loginSuccess.jsp");


    }
}
